package com.wlj.security.core.social.qq.config;

import com.wlj.security.core.social.qq.connect.QQConnectionFactory;
import com.wlj.security.core.properties.QQProperties;
import com.wlj.security.core.properties.WljSecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.social.SocialAutoConfigurerAdapter;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.social.UserIdSource;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.util.Assert;

//ConditionalOnProperty作用:当配置文件里有配置 wlj.security.social.qq.app-id 时以下配置才生效
@Configuration
@ConditionalOnProperty(prefix = "wlj.security.social.qq",name = "app-id")
public class QQAutoConfig extends SocialAutoConfigurerAdapter {

    @Autowired
    private WljSecurityProperties wljSecurityProperties;

    private static class SecurityContextUserIdSource implements UserIdSource {
        private SecurityContextUserIdSource() {
        }

        public String getUserId() {
            SecurityContext context = SecurityContextHolder.getContext();
            Authentication authentication = context.getAuthentication();
            Assert.state(authentication != null, "Unable to get a ConnectionRepository: no user signed in");
            return authentication.getName();
        }
    }

    @Override
    public UserIdSource getUserIdSource() {
        return new QQAutoConfig.SecurityContextUserIdSource();
    }

    @Override
    protected ConnectionFactory<?> createConnectionFactory() {
        QQProperties qq = wljSecurityProperties.getSocial().getQq();
        return new QQConnectionFactory(qq.getProviderId(),qq.getAppId(),qq.getAppSecret());
    }
}
